
package vn.com.tiz.core.task;

import vn.com.tiz.core.utils.DialogUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;

public abstract class AbstractCancellableProgressTask<Params, Progress, Result> extends AbstractCallbackableTask<Params, Progress, Result> {

	protected Activity activity;
	protected ProgressDialog dialog;
	protected DialogInterface.OnCancelListener cancelCallback;


	protected boolean enabledProgressDialog = true;

	public AbstractCancellableProgressTask(Activity activity) {
		super(activity);
		this.activity = activity;
	}


	protected abstract int getProgressMessageId();

	@Override
	protected void onPreExecute() {
		String message = "Loading...";
		try {		
			message = activity.getString(getProgressMessageId());
		} catch (Exception e) {
			// TODO: handle exception
		}		
		
		
		dialog = ProgressDialog.show(activity, null, message);
		//dialog.getWindow().setLayout(actBase.SCREEN_WIDTH - 50, 400);
		dialog.setCancelable(true);
		dialog.setOnKeyListener(DialogUtils.getUnsearchableDialogKeyListener());
		dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			public void onCancel(DialogInterface _dialog) {
				forceCloseDialog();
				cancel(true);

				if (null != cancelCallback) {
					cancelCallback.onCancel(dialog);
				}
			}
		});
	}

	public void cancelTask() {
		this.forceCloseDialog();
		this.cancel(true);
	}

	
	private void forceCloseDialog() {
		if (this.dialog != null) {
			try {
				if (this.dialog.isShowing())
					this.dialog.dismiss();
			} catch (Exception e) {
			}
			this.dialog = null;
		}
	}

	
	@Override
	protected void onPostExecute(Result result) {
		if (null != this.dialog) {
			this.dialog.dismiss();
		}

		super.onPostExecute(result);
	}

		public void setCancelCallback(DialogInterface.OnCancelListener cancelCallback) {
		this.cancelCallback = cancelCallback;
	}

	public void setCancelCallback(final Activity finishActivity) {
		this.cancelCallback = new DialogInterface.OnCancelListener() {
			public void onCancel(DialogInterface dialoginterface) {
				finishActivity.finish();
			}
		};
	}

	public void setEnabledProgressDialog(boolean enabledProgressDialog) {
		this.enabledProgressDialog = enabledProgressDialog;
	}
}